1238D - AB-string - CodeForces Solution


binary search combinatorics dp strings *1900

Please click on ads to support us..

Python Code:

n=int(input())
s=input()

ans=(n-1)*n//2
ab=0
for _ in range(2):
    con=1
    for i in range(n-1):
        if s[i]==s[i+1]:
            con+=1
        else:
            ans-=con
            con=1
            ab+=1
    s=s[::-1]
print(ans+ab//2)

C++ Code:

#include<bits/stdc++.h>
using namespace std;

#define ll long long
#define ull unsigned long long
#define pb push_back
#define foru(i,a,b) for(int i = a; i <= b; i++)
#define ford(i,a,b) for(int i = a; i >= b; i--)
#define fi first
#define se second
#define endl "\n"

typedef pair<ll,ll> ii;
typedef vector<ii> vii;

const int maxn = 3e5 + 7;
const int oo = 1e9 + 7;
const int MOD = 1e9 + 7;
const int block_size = 750;

void init() {
    if(fopen("1238D.inp", "r")) {
        freopen("1238D.inp","r",stdin);
        freopen("1238D.out","w",stdout);
    }
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);
    cout.tie(NULL);
}


int main() {
    init();
    int n; string str;
    cin >> n >> str;

    ll sub = 0;
    for(int i = 0; i < n; i++) {
        for(int j = i + 1; j < n && str[j] != str[i]; j++) sub++;
        for(int j = i - 1; j >= 0 && str[j] != str[i]; j--) sub++;
        if(i > 0 && str[i - 1] != str[i]) sub--;
//        cout << i << ' ' << sub << endl;
    }

    ll res = 1ll * n * (n - 1) / 2 - sub;
    cout << res;
}



Comments

Submit
0 Comments
More Questions

1711A - Perfect Permutation
1701B - Permutation
1692A - Marathon
1066A - Vova and Train
169B - Replacing Digits
171D - Broken checker
380C - Sereja and Brackets
1281B - Azamon Web Services
1702A - Round Down the Price
1681C - Double Sort
12A - Super Agent
1709A - Three Doors
1680C - Binary String
1684B - Z mod X = C
1003A - Polycarp's Pockets
1691B - Shoe Shuffling
1706A - Another String Minimization Problem
1695B - Circle Game
1702B - Polycarp Writes a String from Memory
1701A - Grass Field
489C - Given Length and Sum of Digits
886B - Vlad and Cafes
915A - Garden
356A - Knight Tournament
1330A - Dreamoon and Ranking Collection
1692B - All Distinct
1156C - Match Points
1675A - Food for Animals
1328C - Ternary XOR
1689A - Lex String